package bid

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"strconv"
	"strings"
	"time"
	"wx-api/adx-bid/config"
	"wx-api/adx-bid/model/m_dsp_adv_creative"
	"wx-api/adx-bid/model/m_dsp_adv_plan"
	"wx-api/adx-bid/models/bid/BidModel"
	"wx-api/adx-bid/services/common"
)

func GetTrackUrls(p *BudgetService) {
	if p == nil {
		return
	}
	if p.ResBid == nil {
		return
	}
	timenow := time.Now()

	d := p.Req.GetDevice()
	app := p.Req.GetApp()
	ext_log := &BidModel.LogMsg{
		Id:       p.Req.GetId(),
		Bidid:    p.Req.GetBidId(),
		Impid:    p.Req.GetImp()[0].GetId(),
		Date:     timenow.Format("2006-01-02"),
		DateHour: strconv.Itoa(timenow.Hour()),
		AdxId:    p.Adx.Uqid,
		MediaId:  p.Media.Uqid,
		SlotId:   p.Slot.Uqid,
		PlanId:   p.Plan.Uqid,
		DspId:    p.Dsp.Uqid,
		PosId:    p.Pos.Uqid,
		Syst:     p.Syst,
		Ip: func(a, b string) string {
			if b != "" {
				return b
			}
			return a
		}(d.GetIpv6(), d.GetIp()),
		Os:            d.GetOs(),
		Osv:           d.GetOsv(),
		App:           app.GetBundle(),
		Model:         d.GetModel(),
		Imei:          d.GetImeiMd5(),
		Oaid:          d.GetOaidMd5(),
		Idfa:          d.GetIdfaMd5(),
		Android:       d.GetAndroidIdMd5(),
		Mac:           d.GetMacMd5(),
		Timestamp:     timenow.Unix(),
		MediaRtbPrice: p.MdPrice, //媒体底价
		DspRtbPrice:   p.MSPrice, //发送给上游价格
		DspPrice:      p.DdPrice, //上游返回价格
		MediaPrice:    p.DFPrice, //返回给媒体价格
		Cost:          p.DFPrice, //自有价格
		AdxPv:         int64(p.Adx.PvTm),
		DspPv:         int64(p.Dsp.PvHour),
	}
	kmsg, err := proto.Marshal(ext_log)
	if err != nil {
		fmt.Println("GetTrackUrls proto error:" + err.Error())
		return
	}
	bkmsg, err := common.MsgEncCBCEncrypt(kmsg)
	if err != nil {
		fmt.Println("MsgEncCBCEncrypt proto error:" + err.Error())
		return
	}
	ishttps := false
	if p.Req.GetImp()[0].GetSecure() == 1 {
		ishttps = true
	}
	pvs := GetExtUrl("imp", bkmsg, ishttps)
	pvs += "&tpc=__PRICE__"
	p.ResBid.Views = append(p.ResBid.Views, pvs)
	ck := GetExtUrl("clk", bkmsg, ishttps)
	p.ResBid.Clicks = append(p.ResBid.Clicks, ck)
	if p.ResBid.GetVideo() != nil && p.ResBid.GetVideo().GetUrl() != "" {
		p.ResBid.Video.Ext.Start = append(p.ResBid.Video.Ext.Start, GetExtUrl("vds", bkmsg, ishttps))
		p.ResBid.Video.Ext.End = append(p.ResBid.Video.Ext.End, GetExtUrl("vde", bkmsg, ishttps))
	}
	if p.ResBid.GetDownUrl() != "" {
		p.ResBid.StartDown = append(p.ResBid.StartDown, GetExtUrl("sd", bkmsg, ishttps))
		p.ResBid.EndDown = append(p.ResBid.EndDown, GetExtUrl("ed", bkmsg, ishttps))
		p.ResBid.StartInstall = append(p.ResBid.StartInstall, GetExtUrl("si", bkmsg, ishttps))
		p.ResBid.EndInstall = append(p.ResBid.EndInstall, GetExtUrl("ei", bkmsg, ishttps))
		p.ResBid.Actives = append(p.ResBid.Actives, GetExtUrl("ac", bkmsg, ishttps))
	}
	if p.ResBid.GetDpurl() != "" {
		//p.ResBid.ChDp = append(p.ResBid.ChDp, GetExtUrl("dp", bkmsg, ishttps))
		p.ResBid.DplinksSuccess = append(p.ResBid.DplinksSuccess, GetExtUrl("sdp", bkmsg, ishttps))
		//p.ResBid.ChFdp = append(p.ResBid.ChFdp, GetExtUrl("fdp", bkmsg, ishttps))
	}
	return
}

func GetDspTrackUrls(req *BidModel.BidRequest, bid *BidModel.BidResponse_SeatBid_Bid, syst, media_id, app_id, slot_id string, plan_info *m_dsp_adv_plan.DspAdvPlan, ad_info *m_dsp_adv_creative.DspAdvCreative) {

	timenow := time.Now()

	d := req.GetDevice()
	app := req.GetApp()
	ext_log := &BidModel.LogMsg{
		Id:         req.GetId(),
		Bidid:      req.GetBidId(),
		Impid:      req.GetImp()[0].GetId(),
		Date:       timenow.Format("2006-01-02"),
		DateHour:   strconv.Itoa(timenow.Hour()),
		AdxId:      media_id,
		MediaId:    app_id,
		SlotId:     slot_id,
		AdvId:      plan_info.AdvId,
		PlanId:     plan_info.Uqid,
		CreativeId: ad_info.Uqid,
		Syst:       syst,
		Ip: func(a, b string) string {
			if b != "" {
				return b
			}
			return a
		}(d.GetIpv6(), d.GetIp()),
		Os:         d.GetOs(),
		Osv:        d.GetOsv(),
		App:        app.GetBundle(),
		Model:      d.GetModel(),
		Imei:       d.GetImeiMd5(),
		Oaid:       d.GetOaidMd5(),
		Idfa:       d.GetIdfaMd5(),
		Android:    d.GetAndroidIdMd5(),
		Mac:        d.GetMacMd5(),
		Timestamp:  timenow.Unix(),
		MediaPrice: bid.GetPrice(), //返回给媒体价格
		Cost:       bid.GetPrice(), //自有价格
		AdxPv:      int64(2),
		DspPv:      int64(2),
	}
	kmsg, err := proto.Marshal(ext_log)
	if err != nil {
		fmt.Println("GetTrackUrls proto error:" + err.Error())
		return
	}
	bkmsg, err := common.MsgEncCBCEncrypt(kmsg)
	if err != nil {
		fmt.Println("MsgEncCBCEncrypt proto error:" + err.Error())
		return
	}
	ishttps := false
	if req.GetImp()[0].GetSecure() == 1 {
		ishttps = true
	}
	pvs := GetExtUrl("imp", bkmsg, ishttps)
	pvs += "&tpc=__PRICE__"
	bid.Views = append(bid.Views, pvs)
	ck := GetExtUrl("clk", bkmsg, ishttps)
	bid.Clicks = append(bid.Clicks, ck)
	if bid.GetVideo() != nil && bid.GetVideo().GetUrl() != "" {
		bid.Video.Ext.Start = append(bid.Video.Ext.Start, GetExtUrl("vds", bkmsg, ishttps))
		bid.Video.Ext.End = append(bid.Video.Ext.End, GetExtUrl("vde", bkmsg, ishttps))
	}
	if bid.GetDownUrl() != "" {
		bid.StartDown = append(bid.StartDown, GetExtUrl("sd", bkmsg, ishttps))
		bid.EndDown = append(bid.EndDown, GetExtUrl("ed", bkmsg, ishttps))
		bid.StartInstall = append(bid.StartInstall, GetExtUrl("si", bkmsg, ishttps))
		bid.EndInstall = append(bid.EndInstall, GetExtUrl("ei", bkmsg, ishttps))
		bid.Actives = append(bid.Actives, GetExtUrl("ac", bkmsg, ishttps))
	}
	if bid.GetDpurl() != "" {
		//bid.ChDp = append(bid.ChDp, GetExtUrl("dp", bkmsg, ishttps))
		bid.DplinksSuccess = append(bid.DplinksSuccess, GetExtUrl("sdp", bkmsg, ishttps))
		//bid.ChFdp = append(bid.ChFdp, GetExtUrl("fdp", bkmsg, ishttps))
	}
	return
}

func GetExtUrl(ts, encodekmsg string, ishttp bool) string {
	urlstr := config.GConfig.SysS.TrackUrl
	if ishttp {
		urlstr = strings.Replace(urlstr, "http:", "https:", -1)
	}
	urlstr += "/" + ts + "?tc=" + encodekmsg
	return urlstr
}
